"""
添加slots_count字段到schedule_results表
"""

import os
import sys
import logging
from datetime import datetime

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# 导入Flask应用
from app import create_app, db
from sqlalchemy import text

def add_slots_count_column():
    """添加slots_count字段到schedule_results表"""
    logger.info("开始添加slots_count字段到schedule_results表...")
    
    # 创建Flask应用
    app = create_app()
    
    # 在应用上下文中执行操作
    with app.app_context():
        try:
            # 检查字段是否已存在
            result = db.session.execute(text("SHOW COLUMNS FROM schedule_results LIKE 'slots_count'"))
            if result.rowcount == 0:
                # 添加字段
                db.session.execute(text("ALTER TABLE schedule_results ADD COLUMN slots_count INT NULL"))
                db.session.commit()
                logger.info("成功添加slots_count字段到schedule_results表")
            else:
                logger.info("slots_count字段已存在，无需添加")
                
            return True
        except Exception as e:
            db.session.rollback()
            logger.error(f"添加slots_count字段失败: {str(e)}")
            return False

if __name__ == "__main__":
    # 添加slots_count字段到schedule_results表
    success = add_slots_count_column()
    
    if success:
        print("成功添加slots_count字段到schedule_results表")
    else:
        print("添加slots_count字段失败")
        sys.exit(1)
